
#ifndef __triggerH__
#define __triggerH__

#include "dynamic.h"

namespace WtfEngine
{
	template <typename T>
	struct Comparator {
		typedef typename Meta::Value<T>::tValue tType;

		struct Equal {
			static const int Key = 1;
			inline static bool Test(const tType& a, const tType& b) {
				return (a == b);
			};
		};
		struct NotEqual {
			static const int Key = 2;
			inline static bool Test(const tType& a, const tType& b) {
				return !(a == b);
			};
		};
		struct LessThan {
			static const int Key = 3;
			inline static bool Test(const tType& a, const tType& b) {
				return (a < b);
			};
		};
		struct GreaterThan {
			static const int Key = 4;
			inline static bool Test(const tType& a, const tType& b) {
				return (a > b);
			};
		};
	};

	template <typename tType, class _Comparator = typename Comparator<tType>::Equals>
	class Trigger : public virtual IDynamic, public KeyedEvent<Trigger<tType, _Comparator> >
	{
		typedef Trigger<tType, _Comparator> tThis;
		typedef typename Meta::Value<tType>::tValue tValue;

		const tType * mpValue;
		tValue        mThreshold;

	public:
		Trigger(const tType& rv, const tValue& v)
			: IDynamic(), mpValue(&rv), mThreshold(v) {};
		
		void Update(){
			if(_Comparator::Test(typename Meta::Value<tType>::get(*mpValue), mThreshold)) {
				// Throw the event
				Kernel::GetInstance().ProcessEvent(this);
			};
		};
		
		// Event order - there are two keys here: the value pointer and the threshold value.
		EVENT(tThis, KeyedEvent<tThis>,
			(mpValue == pEv->mpValue
			? (typename Comparator<tType>::Equal::Test(mThreshold, pEv->mThreshold)
			? 0 : (typename Comparator<tType>::LessThan::Test(mThreshold, pEv->mThreshold) ? -1 : 1)
			) : ((int)mpValue - (int)pEv->mpValue)));
	};
};

#endif
